package com.frxuexi.mynews.activity

import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.frxuexi.lib_commom.GlideUtils
import com.frxuexi.mynews.R
import com.frxuexi.mynews.adapter.CommentAdapter
import com.frxuexi.mynews.databinding.ActivityDetailBinding
import com.frxuexi.mynews.intent.NewsIntent
import com.frxuexi.mynews.state.NewsState
import com.frxuexi.mynews.viewmodel.NewsViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch


@Route(path = "/app/DetailActivity")
class DetailActivity : AppCompatActivity() {

    @Autowired
    @JvmField
    var id:String?=null
    lateinit var vm:NewsViewModel
    lateinit var db:ActivityDetailBinding
    var flag:Boolean=false
    lateinit var commentAdapter:CommentAdapter

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        db=ActivityDetailBinding.inflate(layoutInflater)
        setContentView(db.root)
        //接收参数，必须写这行
        ARouter.getInstance().inject(this)
        vm=ViewModelProvider(this).get(NewsViewModel::class.java)

        Log.i("===",id.toString())


        val token = MMKV.defaultMMKV().decodeString("token", "")
        Log.i("===token",token.toString())
        if(token.equals("")){
            ARouter.getInstance().build("/app/LoginActivity").navigation()
            return
        }

        db.deTool.setNavigationOnClickListener {
            finish()
        }

        db.deTool.setOnMenuItemClickListener {
            if(it.itemId==R.id.video){
                Toast.makeText(this@DetailActivity, "点击", Toast.LENGTH_SHORT).show()
            }
            return@setOnMenuItemClickListener true
        }


        commentAdapter= CommentAdapter(R.layout.item_comment)
        db.dRvcomment.apply {
            layoutManager=LinearLayoutManager(this@DetailActivity)
            adapter=commentAdapter
        }

        //收藏
        db.dCollimg.setOnClickListener {
            lifecycleScope.launch {
                vm.channel.send(NewsIntent.newsCollect(id!!.toInt()))
            }
        }

        db.dComment.setOnFocusChangeListener { v, hasFocus ->
            Log.i("===",hasFocus.toString())
            if(hasFocus) {
                db.dGroup.visibility = View.GONE
                db.dPublish.visibility = View.VISIBLE
            }else{
                db.dGroup.visibility=View.VISIBLE
                db.dPublish.visibility=View.GONE
            }
        }

        db.dComment.setOnClickListener {
            if(db.dComment.focusable==View.NOT_FOCUSABLE){
                db.dComment.focusable==View.FOCUSABLE
            }
        }


        db.dPublish.setOnClickListener {
            val comment = db.dComment.text.toString()
            if(comment.isEmpty()){
                return@setOnClickListener
            }
            val map = hashMapOf<String, Any>(
                Pair("content", db.dComment.text.toString()), Pair("nid", id?.toInt()!!),
                Pair("parentid", 0)
            )
            lifecycleScope.launch {
                vm.channel.send(NewsIntent.newsComment(map))
            }
            //清空输入内容
            db.dComment.text.clear()
            db.dComment.focusable=View.NOT_FOCUSABLE
            //关闭键盘
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(db.dComment.getWindowToken(), 0)
        }


        lifecycleScope.launch {
            vm.newsState.collect{
                when(it){
                    is NewsState.onDetailSucess->{ //类型列表数据
                        Log.i("===",it.data.toString())
                        val data = it.data
                        db.dTitle.text=data.title
                        GlideUtils.loadImage(this@DetailActivity,data.imgurl,db.dIv)
                        db.dContent.text=data.content
                        db.dCommnum.text="评论（${data.comments}）"
                        db.dLooknum.text=data.looks.toString()
                        db.dCollnum.text=data.collects.toString()
                        db.dComnum.text=data.comments.toString()
                    }
                    is NewsState.onNewsCollectSucess->{//点赞/取消
                        if(flag){
                            flag=false
                            GlideUtils.loadRoundImage(this@DetailActivity,R.drawable.ic_action_love,db.dCollimg)
                            db.dCollnum.text=(db.dCollnum.text.toString().toInt()-1).toString()
                        }else{
                            flag=true
                            GlideUtils.loadRoundImage(this@DetailActivity,R.drawable.ic_action_loveselect,db.dCollimg)
                            db.dCollnum.text=(db.dCollnum.text.toString().toInt()+1).toString()
                        }
                    }
                    is NewsState.onMyCollectSucess->{//收藏的新闻
                        it.data.forEach {
                            if(it.id==id?.toInt()){
                                //这条新闻，我收藏过
                                flag=true
                                GlideUtils.loadRoundImage(this@DetailActivity,R.drawable.ic_action_loveselect,db.dCollimg)
                            }
                        }
                    }
                    is NewsState.onNewsCommentSucess->{//发布评论成功
                        Toast.makeText(this@DetailActivity, "发布成功", Toast.LENGTH_SHORT).show()
                        vm.channel.send(NewsIntent.getCommentById(id!!.toInt()))
                    }
                    is NewsState.ongetCommentSucess->{//评论列表
                        val list = it.data.sortedByDescending {
                            it.createTime
                        }
                        commentAdapter.data.clear()
                        commentAdapter.data=list.toMutableList()
                        commentAdapter.notifyDataSetChanged()
                    }
                    is NewsState.onError->
                        Log.i("===",it.msg)
                    else -> {}
                }
            }
        }

        lifecycleScope.launch {
            vm.channel.send(NewsIntent.getNewsDetail(id!!.toInt()))
            vm.channel.send(NewsIntent.myCollect)
            vm.channel.send(NewsIntent.getCommentById(id!!.toInt()))
        }

    }
}